package com.java123.t10.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;

public class Client {

	public static void main(String[] args) {
		//tcpClient();
		udpClient();
	}

	public static void tcpClient() {
		try {
			Socket socket = new Socket("127.0.0.1", 9999);
			OutputStream output = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(output);
			pw.write("hello!");
			pw.write("Bye");
			pw.flush();
			socket.shutdownOutput();

			// 获得输入流
			InputStream input = socket.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(input));
			String info = null;
			while ((info = br.readLine()) != null) {
				System.out.println("tcp->服务器回复：" + info);
			}

			// 释放资源
			pw.close();
			output.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void udpClient() {
		try {
			// 服务器的地址、端口号、数据
			InetAddress address = InetAddress.getByName("127.0.0.1");
			int port = 9998;
			byte[] data = "hi,udp server!".getBytes();

			// 创建数据报
			DatagramPacket packet = new DatagramPacket(data, data.length, address, port);

			// 向服务器端发送数据报
			DatagramSocket socket = new DatagramSocket();
			socket.send(packet);
			/*
			 * 接收服务器端响应的数据
			 */
			// 1.创建数据报，用于接收服务器端响应的数据
			byte[] data2 = new byte[1024];
			DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
			// 2.接收服务器响应的数据
			socket.receive(packet2);
			// 3.读取数据
			String reply = new String(data2, 0, packet2.getLength());
			System.out.println("我是客户端，服务器说：" + reply);
			// 4.关闭资源
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
